package com.qubaopen.core.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhcacheUtils {

	/**
	 * 设置缓存
	 */
	public static void setCache(CacheManager manager, String cacheName,
			String key, Object value) {

		if (manager.getCache(cacheName) == null) {
			manager.addCache(cacheName);
		}

		Cache cache = manager.getCache(cacheName);

		cache.put(new Element(key, value));
		// manager.shutdown();

	}

	/**
	 * 获取缓存的值
	 */
	public static Object getCache(CacheManager manager, String cacheName,
			String key) {
		Cache cache = manager.getCache(cacheName);
		if (cache == null)
			return null;

		Element element = cache.get(key);
		// manager.shutdown();

		if (element == null)
			return null;
		else
			return element.getObjectValue();

	}

	/**
	 * 清除缓存
	 */
	public static void removeCache(CacheManager manager, String cacheName,
			String key) {

		Cache cache = manager.getCache(cacheName);
		if (cache != null) {
			cache.remove(key);
		}
	}

	/**
	 * 清除指定模块的所有缓存
	 */
	public static void removeAllCache(CacheManager manager, String cacheName) {

		Cache cache = manager.getCache(cacheName);
		if (cache != null) {
			cache.removeAll();
		}
	}

}
